import React, { Component } from "react";
import {
  Modal,
  Icon,
  Tabs,
  Popover,
  Button,
  Spin,
  Popconfirm,
  message,
} from "antd";
import { messages } from "share/common";
import errorMessage from "share/errorMessage";
import FileViewer from "components/file-viewer";
import Condition from "components/condition";
import wrapGuide from "components/method/wrapGuide";
import ColumnLayout from "components/template/slide-document/column-layout";
import InvoiceNotMatched from "./invoice-not-matched";
import InvoiceToBeChecked from "./invoice-to-be-checked";
import AuditNoticeModal from "./audit-notice-modal";
import CounterModal from "./counter-modal";
import noInvoiceImg from "images/financial-management/file-audit/no-invoice-img.png";
import auditService from "../finance-audit.service";
import "styles/financial-management/finance-audit/invoice-manual-check.scss";
import invoiceBagApproveService from "../../invoice-bag-approve/invoice-bag-approve.service";

const { If, Else } = Condition;

const { ColumnLayoutLeft, ColumnLayoutRight } = ColumnLayout;
const { TabPane } = Tabs;

/**
 * 人工核票组件
 *
 *
 */
class InvoiceManualCheck extends Component {
  state = {
    noticeVisible: false,
    tabKey: this.props.hasNotMatchReceipt ? "NOT_MATCHED" : "TO_BE_CHECKED",
    selectedInvoice: {},
    info: {},
    hasGetInfo: false, //是否已获取到发票信息
    checkLoading: false,
    checkboxKeys: [], //复选框选中的key
    checkCounterList: [], //子组件倒计时列表
  };

  componentDidMount() {
    const { hasNotMatchReceipt } = this.props;
    this.getInfo(hasNotMatchReceipt ? "NOT_MATCHED" : "TO_BE_CHECKED");
    setTimeout(() => {
      wrapGuide(
        {
          ref: this.refs.tipsRef,
          title: messages("expense-14.key157") /*小贴士*/,
          content: (
            <div>
              1.{" "}
              {
                messages(
                  "expense-14.key158"
                ) /*点击键盘上下键/回车/tab可以切换发票*/
              }{" "}
              <br />
              2.{" "}
              {
                messages(
                  "expense-14.key159"
                ) /*切换时自动保存发票并校验发票信息*/
              }
            </div>
          ),
          placement: "bottom",
          inline: "start",
          arrowStyle: {
            left: -8,
          },
        },
        {
          key: "INVOICE_MANUAL_CHECK_GUIDE",
          type: "INCLUDE_MENU",
          total: 1,
        }
      );
    }, 600);
  }

  /**
   *
   * @param type NOT_MATCHED(未匹配)，TO_BE_CHECKED(待核对)，CHECKED(已核对)
   */
  getInfo = (type) => {
    const { entityOID, entityType } = this.props;
    this.setState({ tabKey: type, hasGetInfo: false });
    auditService
      .getManualCheckInfo(entityOID, type, entityType)
      .then((res) => {
        // 列表中未匹配的发票可能是假的未匹配
        // 因为若同一组待核对发票中的其中一张改为未匹配状态，则这张发票实际还是待核对状态
        if (type === "NOT_MATCHED" && res.data.notMatchedNum === 0) {
          this.getInfo("TO_BE_CHECKED");
        } else {
          this.setState({ info: res.data, hasGetInfo: true });
        }
      })
      .catch((e) => {
        console.error(e);
        errorMessage(e.response);
      });
  };

  popoverContent = (
    <div>
      <div
        style={{
          fontSize: 16,
          marginBottom: 4,
          fontWeight: "bolder",
          color: "#1e2126",
        }}
      >
        {messages("expense-14.key157") /*小贴士*/}
      </div>
      <div style={{ color: "#4e5b71" }}>
        1.{" "}
        {messages("expense-14.key158") /*点击键盘上下键/回车/tab可以切换发票*/}{" "}
        <br />
        2. {messages("expense-14.key159") /*切换时自动保存发票并校验发票信息*/}
      </div>
    </div>
  );

  renderCounterModal = (type) => {
    if (localStorage.getItem(`AUDIT_REMIND_${type}`) === "true") {
      return;
    }
    let interval,
      counter = 3;
    const modal = Modal.success({
      content: <CounterModal type={type} />,
      okText: messages("common.ok") /*确定*/,
      onOk: () => {
        clearInterval(interval);
      },
    });
    interval = setInterval(() => {
      counter--;
      if (!counter) {
        clearInterval(interval);
        modal.destroy();
      }
    }, 1000);
  };

  handleCheckSuccess = (notMatchedNum, toBeCheckedNum) => {
    let { info } = this.state;
    if (notMatchedNum > 0 && toBeCheckedNum === 0 && info.toBeCheckedNum > 0) {
      //仅有未匹配发票
      this.renderCounterModal("ONLY_NOT_MATCHED");
      this.changeTab("NOT_MATCHED");
    } else if (
      notMatchedNum === 0 &&
      toBeCheckedNum > 0 &&
      info.notMatchedNum > 0
    ) {
      //仅有待核对发票
      this.renderCounterModal("ONLY_TO_BE_CHECKED");
      this.changeTab("TO_BE_CHECKED");
    } else if (notMatchedNum === 0 && toBeCheckedNum === 0) {
      //全部发票核对成功
      this.renderCounterModal("ALL_CHECK_SUCCESS");
      setTimeout(this.props.onCancel, 1000);
    } else {
      info.notMatchedNum = notMatchedNum;
      info.toBeCheckedNum = toBeCheckedNum;
      this.setState({ info });
    }
  };

  changeTab = (tabKey) => {
    this.setState({ checkboxKeys: [] });
    this.getInfo(tabKey);
  };

  // 更改发票核对状态
  handleCheckInvoice = () => {
    const { entityType, entityOID } = this.props;
    const { checkboxKeys, tabKey } = this.state;
    const params = {
      checkTag: "CHECKED",
      receiptIds: checkboxKeys,
      checkSource: entityType === 5001 ? 0 : 1,
      entityCode: entityOID,
    };
    this.setState({ checkLoading: true });
    invoiceBagApproveService
      .batchCheckInvoice(params)
      .then(() => {
        this.setState({ checkCounterList: checkboxKeys }, () => {
          this.setState({ checkCounterList: [] });
        });
        message.success(
          tabKey === "NOT_MATCHED"
            ? messages("expense-14.key160", {
                arg1: checkboxKeys.length,
              }) /*{arg1} 笔发票更新为已核对*/
            : messages("expense-14.key161", {
                arg1: checkboxKeys.length / 2,
              }) /*{arg1} 组发票更新为已核对*/
        );
      })
      .finally(() => this.setState({ checkLoading: false }));
  };

  renderLeftContent = () => {
    const { visible, entityOID, entityID, entityType, userOID } = this.props;
    const {
      noticeVisible,
      tabKey,
      info,
      hasGetInfo,
      checkboxKeys,
      checkLoading,
      checkCounterList,
    } = this.state;

    const {
      notMatchedNum = 0,
      toBeCheckedNum = 0,
      notMatchedReceipt = {},
      toBeCheckedReceipt = [],
    } = info;
    const selectedLength = (isCheckInvoice) =>
      `<span class="default-color-font">${
        checkboxKeys.length / (isCheckInvoice ? 2 : 1)
      }</span>`;
    const _html =
      tabKey === "NOT_MATCHED"
        ? `已选择 ${selectedLength()} 笔发票`
        : `已选择 ${selectedLength(true)} 组发票`;
    return (
      <div className="invoice-manual-check-left-content">
        <div className="invoice-manual-check-left-content-back">
          <a className="font-default" onClick={this.props.onCancel}>
            <Icon type="left" /> {messages("expense-14.key164") /*人工核票*/}
          </a>
          <Popover content={this.popoverContent} ref="tipsRef">
            <Icon
              type="question-circle-o"
              className="invoice-manual-check-left-content-back-question"
            />
          </Popover>
        </div>
        {notMatchedNum + toBeCheckedNum === 0 ? (
          <Spin />
        ) : (
          <Tabs activeKey={tabKey} onChange={this.changeTab}>
            {notMatchedNum > 0 && (
              <TabPane
                tab={`${
                  messages("expense-14.key165") /*未匹配发票*/
                } (${notMatchedNum})`}
                key="NOT_MATCHED"
              >
                {tabKey === "NOT_MATCHED" && (
                  <InvoiceNotMatched
                    visible={visible && tabKey === "NOT_MATCHED" && hasGetInfo}
                    noticeVisible={noticeVisible}
                    entityID={entityID}
                    entityOID={entityOID}
                    entityType={entityType}
                    checkCounterList={checkCounterList}
                    notMatchedInfo={{
                      ...notMatchedReceipt,
                      notMatchedNum,
                      toBeCheckedNum,
                    }}
                    onSelect={(invoice) =>
                      this.setState({ selectedInvoice: invoice })
                    }
                    onCheckKeysChange={(keys) =>
                      this.setState({ checkboxKeys: keys })
                    }
                    onCheckSuccess={this.handleCheckSuccess}
                  />
                )}
              </TabPane>
            )}
            {toBeCheckedNum > 0 && (
              <TabPane
                tab={`${
                  messages("expense-14.key166") /*待核对发票*/
                } (${toBeCheckedNum})`}
                key="TO_BE_CHECKED"
              >
                {tabKey === "TO_BE_CHECKED" && (
                  <InvoiceToBeChecked
                    visible={
                      visible && tabKey === "TO_BE_CHECKED" && hasGetInfo
                    }
                    entityID={entityID}
                    entityOID={entityOID}
                    entityType={entityType}
                    userOID={userOID}
                    list={toBeCheckedReceipt}
                    checkCounterList={checkCounterList}
                    toBeCheckedInfo={{ notMatchedNum, toBeCheckedNum }}
                    onSelect={(invoice) =>
                      this.setState({ selectedInvoice: invoice })
                    }
                    onCheckKeysChange={(keys) =>
                      this.setState({ checkboxKeys: keys })
                    }
                    onCheckSuccess={this.handleCheckSuccess}
                  />
                )}
              </TabPane>
            )}
          </Tabs>
        )}
        <If value={tabKey === "NOT_MATCHED" && checkboxKeys.length === 0}>
          <div className="footer-operate">
            <Button
              type="primary"
              onClick={() => this.setState({ noticeVisible: true })}
            >
              通知/暂挂
            </Button>
          </div>
        </If>
        <If value={checkboxKeys.length > 0}>
          <div className="footer-operate">
            <span dangerouslySetInnerHTML={{ __html: _html }} />
            <Popconfirm
              title={
                tabKey === "NOT_MATCHED"
                  ? `${checkboxKeys.length}笔发票更新为已核对`
                  : `${checkboxKeys.length / 2}组发票更新为已核对`
              }
              onConfirm={this.handleCheckInvoice}
            >
              <Button
                type="primary"
                loading={checkLoading}
                style={{ marginLeft: 8 }}
              >
                发票已核对
              </Button>
            </Popconfirm>
          </div>
        </If>
        <AuditNoticeModal
          visible={noticeVisible}
          entityOID={entityOID}
          entityType={entityType}
          close={() => this.setState({ noticeVisible: false })}
        />
      </div>
    );
  };

  renderRightContent = () => {
    const { selectedInvoice } = this.state;
    const expenseTypeInfo = selectedInvoice.withReceipt || selectedInvoice;
    const attachments = selectedInvoice.financeReceipt
      ? [selectedInvoice.financeReceipt.slicingAttachment]
      : [selectedInvoice.slicingAttachment];
    const modalParams = {
      mask: false,
      getContainer: () => document.querySelector("#invoice-preview"),
      wrapClassName: "invoice-wrapped-box",
      width: "100%",
      closable: false,
      keyboard: false,
    };
    return (
      <div className="invoice-manual-check-right-content">
        <div className="invoice-manual-check-right-content-title">
          {expenseTypeInfo.expenseTypeName}&nbsp;&nbsp;
          {expenseTypeInfo.invoiceCurrencyCode} {expenseTypeInfo.invoiceAmount}
        </div>
        <div id="invoice-preview">
          <FileViewer
            visible
            urlKey="fileURL"
            valueKey="id"
            markKey="checked"
            attachments={attachments}
            modalParams={modalParams}
          />
        </div>
        <If value={!(attachments[0] && attachments[0].fileURL)}>
          <div className="invoice-manual-check-right-content-empty">
            <img
              src={noInvoiceImg}
              className="invoice-manual-check-right-content-empty-img"
            />
            <div className="invoice-manual-check-right-content-empty-info">
              {messages("expense-14.key168") /*无发票图片*/}
            </div>
          </div>
        </If>
      </div>
    );
  };

  render() {
    const { visible, onCancel } = this.props;
    return (
      <Modal
        visible={visible}
        className="invoice-manual-check"
        onCancel={onCancel}
        width="100%"
        footer={null}
        closable={false}
        mask={false}
        zIndex={5}
      >
        <ColumnLayout leftWidth={480}>
          <ColumnLayoutLeft>{this.renderLeftContent()}</ColumnLayoutLeft>
          <ColumnLayoutRight>{this.renderRightContent()}</ColumnLayoutRight>
        </ColumnLayout>
      </Modal>
    );
  }
}

InvoiceManualCheck.propTypes = {
  visible: React.PropTypes.bool,
  entityID: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string,
  ]),
  entityOID: React.PropTypes.string,
  entityType: React.PropTypes.number,
  hasNotMatchReceipt: React.PropTypes.bool,
  onCancel: React.PropTypes.func,
};

InvoiceManualCheck.defaultProps = {};

export default InvoiceManualCheck;
